/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package metro.jme.lottery.persist;

import javax.microedition.rms.*;

/**
 * This class handles the "low level" part of the storage, everything that is
 * related to the rms.
 * @author pierre
 */
public class RMSUnit {

	public RMSUnit() {
	}

	public static int storeFavouriteSet(byte[] fav, boolean first) {
		RecordStore rs = null;
		int id = -1;
		try {
			rs = RecordStore.openRecordStore(Persist.DBNAME_FAV, true);
			// Store it at the first place
			if (first) {
				rs.addRecord(fav, 0, fav.length);
			} else {
				rs.setRecord(1, fav, 0, fav.length);
			}
			id = 1;
			System.out.println("new fav row created ..");
			rs.closeRecordStore();
		} catch (RecordStoreException e) {
			System.out.println(e);
			e.printStackTrace();
		}
		return id;
	}

	public static byte[] getFavouriteSet() {
		RecordStore rs = null;
		try {
			rs = RecordStore.openRecordStore(Persist.DBNAME_FAV, true);
			int recordSize = rs.getNumRecords();
			if (recordSize > 0) {

				System.out.println("recordSize = " + recordSize);
				byte[] data = null;
				data = new byte[256];
				data = rs.getRecord(1);

				System.out.println("data length : " + data.length);

				System.out.println("close ..");
				System.out.println("data = " + data);
				for (int i = 0; i < data.length; i++) {
					System.out.println("data[i] = " + data[i]);
				}
				return data;
			}
			// Finally, close the RS
			rs.closeRecordStore();
		} catch (RecordStoreException e) {
			System.out.println(e);
		}
		return null;
	}

	/**
	 * 
	 * @param toBeSaved 
	 */
	public static int store(byte[] toBeSaved) {

		RecordStore rs = null;
		int id = -1;
		try {
			rs = RecordStore.openRecordStore(Persist.DBNAME_SETS, true);
			System.out.println("tobs = " + new String(toBeSaved));
			id = rs.addRecord(toBeSaved, 0, toBeSaved.length);
			System.out.println("new set row created ..");
			rs.closeRecordStore();
		} catch (RecordStoreException e) {
			System.out.println(e);
			e.printStackTrace();
		}
		return id;
	}

	public static void delete(String name, int id) throws InvalidRecordIDException {
		try {
			RecordStore rs = RecordStore.openRecordStore(name, false);
			if (rs != null) {
				rs.deleteRecord(id);
			}
			rs.closeRecordStore();
		} catch (RecordStoreException ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 
	 * @return 
	 */
	public static byte[] getSet(int id) {
		RecordStore rs = null;
		byte[] data = null;

		try {
			rs = RecordStore.openRecordStore(Persist.DBNAME_SETS, true);

			data = new byte[256];
			try {
				data = rs.getRecord(id);
				if (data == null) {
					System.err.println("id" + id);
				}
			} catch (InvalidRecordIDException e) {
				e.printStackTrace();
			}

			rs.closeRecordStore();

		} catch (RecordStoreException e) {
			System.out.println(e);
		}

		return data;
	}
}
